<?php
/**
*@author 雷雷
*/

namespace app\admin\controller;


use app\common\controller\Code;
use think\facade\Config;
use think\facade\Db;
use app\admin\model\AuthRule as AuthRuleModel;

class Generate extends Base
{
    /**
     * 一键生成
     * @return \think\Response
     */
    public function codeGeneration(){
        //仅能POST访问
        //        if(!(request()->isPost())){
        //            //重定向
        //            return redirect((string)url('index/index'));
        //        }
        //过滤
        $tableName=request()->param("tableName","","trim");
        $icon=request()->param("icon");
        if ($icon == ""){
            $icon = 'fa-bars';
        }
        if($tableName == null){
            return $this->success([], '缺少关键字~', 400);
        }
        $AuthRule = new AuthRuleModel();
        $original=$tableName;

        $code = new Code();
        try {
            $code->genController($tableName);
            $code->genView($tableName);
            $code->genModel($tableName);
            $code->genAdd($tableName);
            $code->genEdit($tableName);
            $tableName=str_replace("_","",$tableName);
            $index = $tableName."/index";
            $add = $tableName."/add";
            $edit = $tableName."/edit";
            $dele = $tableName."/delete";
            $tableComment = $this->getTableComment($original);
            $tableComment = $tableComment[0]['Comment'];
            $title = $tableComment."管理";
            $indexTitle = $tableComment."首页";
            $indexAdd = $tableComment."添加";
            $indexEdit = $tableComment."编辑";
            $indexDelete = $tableComment."删除";
                $data = [
                    'type'=>'menu',
                    'pid'=>19,
                    'name'=>'',
                    'title'=>$title,
                    'icon' =>$icon
                ];
                $id = $AuthRule->insertGetId($data);
                    $indexList = [
                        'type'=>'menu',
                        'pid'=>$id,
                        'name'=>$index,
                        'title'=>$indexTitle,
                        'icon' =>'s'
                    ];
                    $idx = $AuthRule->insertGetId($indexList);
                        $list = [
                            ['type'=>'file','pid'=>$idx,'name'=>$add,'title'=>$indexAdd,'icon' =>''],
                            ['type'=>'file','pid'=>$idx,'name'=>$edit,'title'=>$indexEdit,'icon' =>''],
                            ['type'=>'file','pid'=>$idx,'name'=>$dele,'title'=>$indexDelete,'icon' =>'']
                        ];
                        $AuthRule->saveAll($list);
                return $this->success([],'成功',0,200);

        }catch (\Exception $e){
            halt($e);
            return $this->success([],'失败',0,400);
        }

    }
    private function getTableComment($tableName){
        $str = "SHOW TABLE STATUS LIKE '$tableName'";
        return Db::query($str);
    }

}